const Path = require('path')
const Fs = require('fs')
const templateRender = require('json-templater/string')
const componentNameList = []
const componentImportList = []
const buildEntries = {}

const COMPONENT_PATH = Path.join(__dirname, '../src/packages')

console.info('start')

Fs.readdirSync(COMPONENT_PATH).forEach(dirName => {
  if (dirName === 'index.js') return
  Fs.readdirSync(Path.join(COMPONENT_PATH, dirName)).forEach(fileName => {
    const REG = new RegExp(/\.(vue | js)$/g);
    if (!['index.vue', 'index.js'].includes(fileName)) return
    const COMPONENT_NAME = dirName.replace(REG, '')
    componentImportList.push(
      `import ${COMPONENT_NAME} from "./${dirName}/${fileName}";`
    )
    buildEntries[COMPONENT_NAME] = `./src/packages/${dirName}/${fileName}`
    componentNameList.push(COMPONENT_NAME)
  })
})

const outputContent = `/* 注意：本文件是由 config/build-entry.js 自动生成的！不要手动修改 */
import { 
  provideGlobalConfig,
  ElLoading as NstdLoading,
  ElMessage as NstdMessage,
  ElMessageBox as NstdMessageBox,
  ElNotification as NstdNotification,
  genFileId
} from 'element-plus'
import { 
  AddLocation,
  Aim,
  AlarmClock,
  Apple,
  ArrowDown,
  ArrowDownBold,
  ArrowLeft,
  ArrowLeftBold,
  ArrowRight,
  ArrowRightBold,
  ArrowUp,
  ArrowUpBold,
  Avatar,
  Back,
  Baseball,
  Basketball,
  Bell,
  BellFilled,
  Bicycle,
  Bottom,
  BottomLeft,
  BottomRight,
  Bowl,
  Box,
  Briefcase,
  Brush,
  BrushFilled,
  Burger,
  Calendar,
  Camera,
  CameraFilled,
  CaretBottom,
  CaretLeft,
  CaretRight,
  CaretTop,
  Cellphone,
  ChatDotRound,
  ChatDotSquare,
  ChatLineRound,
  ChatLineSquare,
  ChatRound,
  ChatSquare,
  Check,
  Checked,
  Cherry,
  Chicken,
  ChromeFilled,
  CircleCheck,
  CircleCheckFilled,
  CircleClose,
  CircleCloseFilled,
  CirclePlus,
  CirclePlusFilled,
  Clock,
  Close,
  CloseBold,
  Cloudy,
  Coffee,
  CoffeeCup,
  Coin,
  ColdDrink,
  Collection,
  CollectionTag,
  Comment,
  Compass,
  Connection,
  Coordinate,
  CopyDocument,
  Cpu,
  CreditCard,
  Crop,
  DArrowLeft,
  DArrowRight,
  DCaret,
  DataAnalysis,
  DataBoard,
  DataLine,
  Delete,
  DeleteFilled,
  DeleteLocation,
  Dessert,
  Discount,
  Dish,
  DishDot,
  Document,
  DocumentAdd,
  DocumentChecked,
  DocumentCopy,
  DocumentDelete,
  DocumentRemove,
  Download,
  Drizzling,
  Edit,
  EditPen,
  Eleme,
  ElemeFilled,
  ElementPlus,
  Expand,
  Failed,
  Female,
  Files,
  Film,
  Filter,
  Finished,
  FirstAidKit,
  Flag,
  Fold,
  Folder,
  FolderAdd,
  FolderChecked,
  FolderDelete,
  FolderOpened,
  FolderRemove,
  Food,
  Football,
  ForkSpoon,
  Fries,
  FullScreen,
  Goblet,
  GobletFull,
  GobletSquare,
  GobletSquareFull,
  GoldMedal,
  Goods,
  GoodsFilled,
  Grape,
  Grid,
  Guide,
  Handbag,
  Headset,
  Help,
  HelpFilled,
  Hide,
  Histogram,
  HomeFilled,
  HotWater,
  House,
  IceCream,
  IceCreamRound,
  IceCreamSquare,
  IceDrink,
  IceTea,
  InfoFilled,
  Iphone,
  Key,
  KnifeFork,
  Lightning,
  Link,
  List,
  Loading,
  Location,
  LocationFilled,
  LocationInformation,
  Lock,
  Lollipop,
  MagicStick,
  Magnet,
  Male,
  Management,
  MapLocation,
  Medal,
  Memo,
  Menu,
  Message,
  MessageBox,
  Mic,
  Microphone,
  MilkTea,
  Minus,
  Money,
  Monitor,
  Moon,
  MoonNight,
  More,
  MoreFilled,
  MostlyCloudy,
  Mouse,
  Mug,
  Mute,
  MuteNotification,
  NoSmoking,
  Notebook,
  Notification,
  Odometer,
  OfficeBuilding,
  Open,
  Operation,
  Opportunity,
  Orange,
  Paperclip,
  PartlyCloudy,
  Pear,
  Phone,
  PhoneFilled,
  Picture,
  PictureFilled,
  PictureRounded,
  PieChart,
  Place,
  Platform,
  Plus,
  Pointer,
  Position,
  Postcard,
  Pouring,
  Present,
  PriceTag,
  Printer,
  Promotion,
  QuartzWatch,
  QuestionFilled,
  Rank,
  Reading,
  ReadingLamp,
  Refresh,
  RefreshLeft,
  RefreshRight,
  Refrigerator,
  Remove,
  RemoveFilled,
  Right,
  ScaleToOriginal,
  School,
  Scissor,
  Search,
  Select,
  Sell,
  SemiSelect,
  Service,
  SetUp,
  Setting,
  Share,
  Ship,
  Shop,
  ShoppingBag,
  ShoppingCart,
  ShoppingCartFull,
  ShoppingTrolley,
  Smoking,
  Soccer,
  SoldOut,
  Sort,
  SortDown,
  SortUp,
  Stamp,
  Star,
  StarFilled,
  Stopwatch,
  SuccessFilled,
  Sugar,
  Suitcase,
  SuitcaseLine,
  Sunny,
  Sunrise,
  Sunset,
  Switch,
  SwitchButton,
  SwitchFilled,
  TakeawayBox,
  Ticket,
  Tickets,
  Timer,
  ToiletPaper,
  Tools,
  Top,
  TopLeft,
  TopRight,
  TrendCharts,
  Trophy,
  TrophyBase,
  TurnOff,
  Umbrella,
  Unlock,
  Upload,
  UploadFilled,
  User,
  UserFilled,
  Van,
  VideoCamera,
  VideoCameraFilled,
  VideoPause,
  VideoPlay,
  View,
  Wallet,
  WalletFilled,
  WarnTriangleFilled,
  Warning,
  WarningFilled,
  Watch,
  Watermelon,
  WindPower,
  ZoomIn,
  ZoomOut
} from '@element-plus/icons-vue'


{{importList}}

const COMPONENTS = [
  {{nameList}},
  NstdLoading,
  NstdMessage,
  NstdMessageBox,
  NstdNotification,
  genFileId,
  // 图标
  AddLocation,
  Aim,
  AlarmClock,
  Apple,
  ArrowDown,
  ArrowDownBold,
  ArrowLeft,
  ArrowLeftBold,
  ArrowRight,
  ArrowRightBold,
  ArrowUp,
  ArrowUpBold,
  Avatar,
  Back,
  Baseball,
  Basketball,
  Bell,
  BellFilled,
  Bicycle,
  Bottom,
  BottomLeft,
  BottomRight,
  Bowl,
  Box,
  Briefcase,
  Brush,
  BrushFilled,
  Burger,
  Calendar,
  Camera,
  CameraFilled,
  CaretBottom,
  CaretLeft,
  CaretRight,
  CaretTop,
  Cellphone,
  ChatDotRound,
  ChatDotSquare,
  ChatLineRound,
  ChatLineSquare,
  ChatRound,
  ChatSquare,
  Check,
  Checked,
  Cherry,
  Chicken,
  ChromeFilled,
  CircleCheck,
  CircleCheckFilled,
  CircleClose,
  CircleCloseFilled,
  CirclePlus,
  CirclePlusFilled,
  Clock,
  Close,
  CloseBold,
  Cloudy,
  Coffee,
  CoffeeCup,
  Coin,
  ColdDrink,
  Collection,
  CollectionTag,
  Comment,
  Compass,
  Connection,
  Coordinate,
  CopyDocument,
  Cpu,
  CreditCard,
  Crop,
  DArrowLeft,
  DArrowRight,
  DCaret,
  DataAnalysis,
  DataBoard,
  DataLine,
  Delete,
  DeleteFilled,
  DeleteLocation,
  Dessert,
  Discount,
  Dish,
  DishDot,
  Document,
  DocumentAdd,
  DocumentChecked,
  DocumentCopy,
  DocumentDelete,
  DocumentRemove,
  Download,
  Drizzling,
  Edit,
  EditPen,
  Eleme,
  ElemeFilled,
  ElementPlus,
  Expand,
  Failed,
  Female,
  Files,
  Film,
  Filter,
  Finished,
  FirstAidKit,
  Flag,
  Fold,
  Folder,
  FolderAdd,
  FolderChecked,
  FolderDelete,
  FolderOpened,
  FolderRemove,
  Food,
  Football,
  ForkSpoon,
  Fries,
  FullScreen,
  Goblet,
  GobletFull,
  GobletSquare,
  GobletSquareFull,
  GoldMedal,
  Goods,
  GoodsFilled,
  Grape,
  Grid,
  Guide,
  Handbag,
  Headset,
  Help,
  HelpFilled,
  Hide,
  Histogram,
  HomeFilled,
  HotWater,
  House,
  IceCream,
  IceCreamRound,
  IceCreamSquare,
  IceDrink,
  IceTea,
  InfoFilled,
  Iphone,
  Key,
  KnifeFork,
  Lightning,
  Link,
  List,
  Loading,
  Location,
  LocationFilled,
  LocationInformation,
  Lock,
  Lollipop,
  MagicStick,
  Magnet,
  Male,
  Management,
  MapLocation,
  Medal,
  Memo,
  Menu,
  Message,
  MessageBox,
  Mic,
  Microphone,
  MilkTea,
  Minus,
  Money,
  Monitor,
  Moon,
  MoonNight,
  More,
  MoreFilled,
  MostlyCloudy,
  Mouse,
  Mug,
  Mute,
  MuteNotification,
  NoSmoking,
  Notebook,
  Notification,
  Odometer,
  OfficeBuilding,
  Open,
  Operation,
  Opportunity,
  Orange,
  Paperclip,
  PartlyCloudy,
  Pear,
  Phone,
  PhoneFilled,
  Picture,
  PictureFilled,
  PictureRounded,
  PieChart,
  Place,
  Platform,
  Plus,
  Pointer,
  Position,
  Postcard,
  Pouring,
  Present,
  PriceTag,
  Printer,
  Promotion,
  QuartzWatch,
  QuestionFilled,
  Rank,
  Reading,
  ReadingLamp,
  Refresh,
  RefreshLeft,
  RefreshRight,
  Refrigerator,
  Remove,
  RemoveFilled,
  Right,
  ScaleToOriginal,
  School,
  Scissor,
  Search,
  Select,
  Sell,
  SemiSelect,
  Service,
  SetUp,
  Setting,
  Share,
  Ship,
  Shop,
  ShoppingBag,
  ShoppingCart,
  ShoppingCartFull,
  ShoppingTrolley,
  Smoking,
  Soccer,
  SoldOut,
  Sort,
  SortDown,
  SortUp,
  Stamp,
  Star,
  StarFilled,
  Stopwatch,
  SuccessFilled,
  Sugar,
  Suitcase,
  SuitcaseLine,
  Sunny,
  Sunrise,
  Sunset,
  Switch,
  SwitchButton,
  SwitchFilled,
  TakeawayBox,
  Ticket,
  Tickets,
  Timer,
  ToiletPaper,
  Tools,
  Top,
  TopLeft,
  TopRight,
  TrendCharts,
  Trophy,
  TrophyBase,
  TurnOff,
  Umbrella,
  Unlock,
  Upload,
  UploadFilled,
  User,
  UserFilled,
  Van,
  VideoCamera,
  VideoCameraFilled,
  VideoPause,
  VideoPlay,
  View,
  Wallet,
  WalletFilled,
  WarnTriangleFilled,
  Warning,
  WarningFilled,
  Watch,
  Watermelon,
  WindPower,
  ZoomIn,
  ZoomOut
];
const install = function (App, options) {
  if (options) provideGlobalConfig(options, App, true)
  COMPONENTS.forEach(component => {
    App.component(component.name, component)
  })
}

// if (typeof window !== 'undefined' && window.Vue) {
//   install(window.Vue)
// }
export {
  {{exportComp}},
  NstdLoading,
  NstdMessage,
  NstdMessageBox,
  NstdNotification,
  genFileId,
  // 图标
  AddLocation,
  Aim,
  AlarmClock,
  Apple,
  ArrowDown,
  ArrowDownBold,
  ArrowLeft,
  ArrowLeftBold,
  ArrowRight,
  ArrowRightBold,
  ArrowUp,
  ArrowUpBold,
  Avatar,
  Back,
  Baseball,
  Basketball,
  Bell,
  BellFilled,
  Bicycle,
  Bottom,
  BottomLeft,
  BottomRight,
  Bowl,
  Box,
  Briefcase,
  Brush,
  BrushFilled,
  Burger,
  Calendar,
  Camera,
  CameraFilled,
  CaretBottom,
  CaretLeft,
  CaretRight,
  CaretTop,
  Cellphone,
  ChatDotRound,
  ChatDotSquare,
  ChatLineRound,
  ChatLineSquare,
  ChatRound,
  ChatSquare,
  Check,
  Checked,
  Cherry,
  Chicken,
  ChromeFilled,
  CircleCheck,
  CircleCheckFilled,
  CircleClose,
  CircleCloseFilled,
  CirclePlus,
  CirclePlusFilled,
  Clock,
  Close,
  CloseBold,
  Cloudy,
  Coffee,
  CoffeeCup,
  Coin,
  ColdDrink,
  Collection,
  CollectionTag,
  Comment,
  Compass,
  Connection,
  Coordinate,
  CopyDocument,
  Cpu,
  CreditCard,
  Crop,
  DArrowLeft,
  DArrowRight,
  DCaret,
  DataAnalysis,
  DataBoard,
  DataLine,
  Delete,
  DeleteFilled,
  DeleteLocation,
  Dessert,
  Discount,
  Dish,
  DishDot,
  Document,
  DocumentAdd,
  DocumentChecked,
  DocumentCopy,
  DocumentDelete,
  DocumentRemove,
  Download,
  Drizzling,
  Edit,
  EditPen,
  Eleme,
  ElemeFilled,
  ElementPlus,
  Expand,
  Failed,
  Female,
  Files,
  Film,
  Filter,
  Finished,
  FirstAidKit,
  Flag,
  Fold,
  Folder,
  FolderAdd,
  FolderChecked,
  FolderDelete,
  FolderOpened,
  FolderRemove,
  Food,
  Football,
  ForkSpoon,
  Fries,
  FullScreen,
  Goblet,
  GobletFull,
  GobletSquare,
  GobletSquareFull,
  GoldMedal,
  Goods,
  GoodsFilled,
  Grape,
  Grid,
  Guide,
  Handbag,
  Headset,
  Help,
  HelpFilled,
  Hide,
  Histogram,
  HomeFilled,
  HotWater,
  House,
  IceCream,
  IceCreamRound,
  IceCreamSquare,
  IceDrink,
  IceTea,
  InfoFilled,
  Iphone,
  Key,
  KnifeFork,
  Lightning,
  Link,
  List,
  Loading,
  Location,
  LocationFilled,
  LocationInformation,
  Lock,
  Lollipop,
  MagicStick,
  Magnet,
  Male,
  Management,
  MapLocation,
  Medal,
  Memo,
  Menu,
  Message,
  MessageBox,
  Mic,
  Microphone,
  MilkTea,
  Minus,
  Money,
  Monitor,
  Moon,
  MoonNight,
  More,
  MoreFilled,
  MostlyCloudy,
  Mouse,
  Mug,
  Mute,
  MuteNotification,
  NoSmoking,
  Notebook,
  Notification,
  Odometer,
  OfficeBuilding,
  Open,
  Operation,
  Opportunity,
  Orange,
  Paperclip,
  PartlyCloudy,
  Pear,
  Phone,
  PhoneFilled,
  Picture,
  PictureFilled,
  PictureRounded,
  PieChart,
  Place,
  Platform,
  Plus,
  Pointer,
  Position,
  Postcard,
  Pouring,
  Present,
  PriceTag,
  Printer,
  Promotion,
  QuartzWatch,
  QuestionFilled,
  Rank,
  Reading,
  ReadingLamp,
  Refresh,
  RefreshLeft,
  RefreshRight,
  Refrigerator,
  Remove,
  RemoveFilled,
  Right,
  ScaleToOriginal,
  School,
  Scissor,
  Search,
  Select,
  Sell,
  SemiSelect,
  Service,
  SetUp,
  Setting,
  Share,
  Ship,
  Shop,
  ShoppingBag,
  ShoppingCart,
  ShoppingCartFull,
  ShoppingTrolley,
  Smoking,
  Soccer,
  SoldOut,
  Sort,
  SortDown,
  SortUp,
  Stamp,
  Star,
  StarFilled,
  Stopwatch,
  SuccessFilled,
  Sugar,
  Suitcase,
  SuitcaseLine,
  Sunny,
  Sunrise,
  Sunset,
  Switch,
  SwitchButton,
  SwitchFilled,
  TakeawayBox,
  Ticket,
  Tickets,
  Timer,
  ToiletPaper,
  Tools,
  Top,
  TopLeft,
  TopRight,
  TrendCharts,
  Trophy,
  TrophyBase,
  TurnOff,
  Umbrella,
  Unlock,
  Upload,
  UploadFilled,
  User,
  UserFilled,
  Van,
  VideoCamera,
  VideoCameraFilled,
  VideoPause,
  VideoPlay,
  View,
  Wallet,
  WalletFilled,
  WarnTriangleFilled,
  Warning,
  WarningFilled,
  Watch,
  Watermelon,
  WindPower,
  ZoomIn,
  ZoomOut
}
export default {
  install,
  provideGlobalConfig,
}
`

const componentJSON = `{\n{{list}}\n}`

const schema = `
[{"title":"通用","type":"layout","show":true,"icon":"appstore","children":[{"type":"input","name":"布局","show":true,"children":[{{list}}]}]}]
`
try {
  Fs.writeFileSync(
    Path.join(COMPONENT_PATH, 'index.js'),
    templateRender(outputContent, {
      version: process.env.VERSION || require('../package.json').version,
      importList: componentImportList.join('\n'),
      nameList: componentNameList.join(',\n  '),
      exportComp: `${componentNameList.join(',\n  ')}`,
    })
  )
  Fs.writeFileSync(
    Path.join(__dirname, 'components.json'),
    templateRender(componentJSON, {
      list: Object.keys(buildEntries)
        .map(key => {
          return `  "${key}": "${buildEntries[key]}"`
        })
        .join(',\n'),
    })
  )
  Fs.writeFileSync(
    Path.join(__dirname, 'element.json'),
    templateRender(schema, {
      list: Object.keys(buildEntries)
        .map(key => {
          return `
            {"component":"${key}","title":"${key}","thumbnail":"http://192.168.1.14:19000/dmp-dev-public-front-files/el-form.png","npm":{"package":"","version":"0.0.1","exportName":"NcElForm","main":"","destructuring":true,"subName":""},"slots":{"default":{"title":"默认","description":"默认插槽"}},"options":{},"children":[],"props":{"options":{"defaultModel":"123"}},"events":{},"configure":{"props":[]}}
                           
            `
        })
        .join(',\n'),
    })
  )
} catch (e) {
  console.error(e)
}
